/*
###############################################################################################
#                                                                                             # 
# The Page is used by the doctors who want to Register with the Site.This Page                #
# contains all the General Information about the doctor.                                      #
#                                                                                             #
#                                                                                             #
#                                                                                             #
###############################################################################################
*/
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System;
using SiteManager;
using System.Text;
using System.IO;

public partial class Ad_Doctor : System.Web.UI.Page
{
    // creating an instance of manager class
    Manager mgr = new Manager(true,"ConnectionString");
    public int Doctorid = 0;
    public string hospName = "";
    public string hospTEXT = ""; //this variable is used to fill the hdnHospital (Hidden Field) to provide the hospital details while saving

    # region Page load
    localFunction lFunction;
    protected void Page_Load(object sender, EventArgs e)
    {       
        btnAddInsurance.Attributes.Add("onclick", "window.open('../admin/Insurance_Add.aspx',null,'height=200,width=450,status=yes,toolbar=no,menubar=no,location=no');return false;");
        lFunction = new localFunction();
        if (ViewState["Action"] == null)
            ViewState["Action"] = Session["pageFromOrAction"];
        if (Request.QueryString["id"] != null)
        {
            try
            {
                Doctorid = Convert.ToInt32(Request.QueryString["id"]);
                lblHeading.Text = "Update Doctor";
            }
            catch { }
        }

        if (!Page.IsPostBack)
        {
            ViewState["Count"] = 1;
            // Session["InsId"] used to store the Insurance Ids of the Insurance companies added using 
            // Insurance_Add module
            Session["InsId"] = "";

            trError.Visible = false;
            FillControls(Doctorid);
        }
    }
   
    # endregion

    # region FillControls
    /// <summary>
    /// this fills all drop down list adn user information 
    /// </summary>
    /// <param name="id"></param>
    public void FillControls(int id)
    {

        int tYear = DateTime.Today.Year;
        for (int i = 1950; i <= tYear; i++)
        {
            ddlGradYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

        // mgr.BindList("select countrycode,countryname from tbl_country", "countryname", "countrycode", ddlCountry, "select");
        mgr.BindList("select [countryname],countrycode from tbl_country where(countrycode='US')OR (countrycode='CA') order by [countryname]", "countryname", "countrycode", ddlCountry, "select");
        ddlState.Items.Insert(0, new ListItem("select", "0"));
        mgr.BindList("select stateid,name from tbl_states  order by name", "Name", "StateId", ddlState, "select");
        //binding ddlSpeciality drop downs

        //mgr.BindListBox("select id,name from tbl_speciality", "name", "id", lstAbms, "select");
        mgr.BindList("select id,name from tbl_MajorActivity order by name", "name", "id", ddlMajorActivity, "select");


        mgr.BindListBox("select id,name from tbl_InsuranceCompanies order by name", "name", "Id", lstInsurance, "select");
        lstInsurance.Items.Add(new ListItem("--NONE--", "-1"));




        ddlAdvTraining.Items.Add(new ListItem("Yes", "Y"));
        ddlAdvTraining.Items.Add(new ListItem("No", "N"));

        ddlnewPat.Items.Add(new ListItem("Yes", "1"));
        ddlnewPat.Items.Add(new ListItem("No", "0"));

        //Edit a doctor's info
        if (id > 0)
        {
            DataSet ds = mgr.ExecuteQuery("select * from tbl_doctors where  isdelete=0 and id='" + id + "';SELECT InsuranceID FROM tbl_Doctor_Insurance WHERE DoctorID='" + id + "'", "tblDoctor");
            //lnkMedSch.Visible = false;
            //lnkMedSchClear.Visible = false;
            //lnkFellow.Visible = false;
            //lnkFellowClear.Visible = false;
            //lnkRes.Visible = false;
            //lnkResClear.Visible = false;

            if (ds.Tables[0].Rows.Count > 0)
            {
                txtFname.Text = ds.Tables[0].Rows[0]["fname"].ToString();
                txtMName.Text = ds.Tables[0].Rows[0]["mname"].ToString();
                txtLName.Text = ds.Tables[0].Rows[0]["lname"].ToString();
                txtEmail.Text = ds.Tables[0].Rows[0]["email"].ToString();
                ViewState["email"] = txtEmail.Text;
                txtEmail.Attributes.Add("value", ds.Tables[0].Rows[0]["email"].ToString());
                txtPwd1.Attributes.Add("value", ds.Tables[0].Rows[0]["Password"].ToString());
                txtpwd2.Attributes.Add("value", ds.Tables[0].Rows[0]["Password"].ToString());

                txtTitle.Text = ds.Tables[0].Rows[0]["Title"].ToString();
                bool ss = ds.Tables[0].Rows[0]["gender"].ToString().Trim().Equals("M") ? rbGender.Checked = true : rbGender2.Checked = true;
                txtLanguages.Text = ds.Tables[0].Rows[0]["Languages"].ToString();
                txtPhone.Text = ds.Tables[0].Rows[0]["Phone"].ToString();
                txtFax.Text = ds.Tables[0].Rows[0]["Fax"].ToString();
                txtAddress1.Text = ds.Tables[0].Rows[0]["Address1"].ToString();
                txtAddress2.Text = ds.Tables[0].Rows[0]["Address2"].ToString();
                txtCity.Text = ds.Tables[0].Rows[0]["City"].ToString();
                //txtState.Text = ds.Tables[0].Rows[0]["State"].ToString();
                txtCounty.Text = ds.Tables[0].Rows[0]["County"].ToString();
                txtZipCode.Text = ds.Tables[0].Rows[0]["ZipCode"].ToString();
                txtPhoto.Text = ds.Tables[0].Rows[0]["photo"].ToString(); ;
                

                if (ds.Tables[0].Rows[0]["ResidencyTraining"].ToString().Trim().Length > 0)
                {
                    string[] ArrRes = ds.Tables[0].Rows[0]["ResidencyTraining"].ToString().Trim().Split(',');
                    for (int i = 0; i < ArrRes.Length; i++)
                    {
                        if (ArrRes[i].ToString().Trim().Length > 0)
                            try
                            {
                                //(lst_res.Items.FindByValue(ArrRes[i].ToString())).Selected = true;
                            }
                            catch
                            {
                                //(lst_res.Items.FindByValue("-1")).Selected = true;

                            }
                    }
                }
                
                txtGroupPractise.Text = ds.Tables[0].Rows[0]["GroupPractice"].ToString();
                txtMsa.Text = ds.Tables[0].Rows[0]["Msa"].ToString();
                txtCmsa.Text = ds.Tables[0].Rows[0]["Cmsa"].ToString();

                bool test = ds.Tables[0].Rows[0]["Abms_CertificationID"].ToString().Equals("True") ? rbtAbms1.Checked = true : rbtAbms2.Checked = true;

                txtUpin.Text = ds.Tables[0].Rows[0]["upin"].ToString();
               
                txtAwards.Text = ds.Tables[0].Rows[0]["Awards"].ToString();

                if (ds.Tables[0].Rows[0]["AdvancedTraining"].ToString().Trim().Equals("N"))
                {
                    ddlAdvTraining.Items.FindByValue("N").Selected = true;
                }
                else
                {
                    ddlAdvTraining.Items.FindByValue("Y").Selected = true;
                }


                if (ds.Tables[0].Rows[0]["AcceptNew"].ToString().Trim().Equals("True"))
                {
                    ddlnewPat.Items.FindByValue("1").Selected = true;
                }
                else
                {
                    ddlnewPat.Items.FindByValue("0").Selected = true;
                }
               

                //string CountryCode = ds.Tables[0].Rows[0]["CountryId"].ToString().Trim();
                string CountryCode = Convert.ToString(ds.Tables[0].Rows[0]["CountryId"]);
                string StateCode = ds.Tables[0].Rows[0]["State"].ToString().Trim();
                string SpecialityID = ds.Tables[0].Rows[0]["SpecialityID"].ToString().Trim();
                string PrimarySpecialityID = ds.Tables[0].Rows[0]["PrimarySpecialityID"].ToString().Trim();
                string SecondarySpecialityID = ds.Tables[0].Rows[0]["SecondarySpecialityID"].ToString().Trim();
                string MajorActivityId = ds.Tables[0].Rows[0]["MajorActivityID"].ToString().Trim();

              
                if (ds.Tables.Count > 1 && ds.Tables[1].Rows.Count > 0)
                {
                    for (int ind = 0; ind < ds.Tables[1].Rows.Count; ind++)
                    {
                        if (lstInsurance.Items.FindByValue(ds.Tables[1].Rows[ind][0].ToString()) != null)
                            lstInsurance.Items.FindByValue(ds.Tables[1].Rows[ind][0].ToString()).Selected = true;
                    }
                }
               

                try
                {
                    ddlCountry.SelectedValue = CountryCode;
                    ddlState.SelectedValue = StateCode;
                    //ddlSpeciality.SelectedValue = SpecialityID;
                    //ddlPSpeciality.SelectedValue = PrimarySpecialityID;
                    //ddlSSpeciality.SelectedValue = SecondarySpecialityID;
                    ddlMajorActivity.SelectedValue = MajorActivityId;
                    ddlGradYear.SelectedValue = ds.Tables[0].Rows[0]["GraduationYear"].ToString().Trim();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.ToString());
                }
              
            }
            else
            {
                return;
            }
        }

    }
    # endregion
    
    protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        string tSpecialityID = Request.Form[GetHTMLNameById(hdnSpecialty.ClientID, hdnSpecialty.ID)];//Request.Form[ddlSpeciality.ClientID.Replace('_', '$')]; //ddlSpeciality.SelectedItem.Value;

        //Server Side Validation 
        Validation validateForm = new Validation();
        
        validateForm.AddValidation(txtGroupPractise.Text, Validation.ValidationCommand.maxlen, "GroupPractice Maximum Length is Only 1000 Characters", "999");

        #region Form submitted finallly
        string tCost = ddlCost.SelectedValue;
        string tFName = txtFname.Text.Replace("'", "''").Trim();
        string tMName = txtMName.Text.Replace("'", "''").Trim();
        string tLName = txtLName.Text.Replace("'", "''").Trim();
        string tEmail = txtEmail.Text.Replace("'", "''").Trim();
        string tPassword = ViewState["Pwd"].ToString(); //txtPwd1.Text.Replace("'", "''").Trim();
        string tTitle = txtTitle.Text.Replace("'", "''").Trim();
        string tGender = rbGender.Checked ? "M" : "F";
        string tLanguages = txtLanguages.Text.Replace("'", "''").Trim();
        string tPhone = txtPhone.Text.Replace("'", "''").Trim();
        string tFax = txtFax.Text.Replace("'", "''").Trim();
        string tAddress1 = txtAddress1.Text.Replace("'", "''").Trim();
        string tAddress2 = txtAddress2.Text.Replace("'", "''").Trim();
        string tCity = txtCity.Text.Replace("'", "''").Trim();
        string tState = ddlState.SelectedItem.Value;
        string tCountryId = ddlCountry.SelectedItem.Value;
        string tCounty = txtCounty.Text.Replace("'", "''").Trim();
        string tZipCode = txtZipCode.Text.Replace("'", "''");
        string tGraduationYear = ddlGradYear.SelectedItem.Text;
        string lst_hospital_HTMLName = GetHTMLNameById(hdnHospital.ClientID, hdnHospital.ID);
        string tHospitalName = Request.Form[lst_hospital_HTMLName].ToString().Replace("[Clear]", ";").Replace("[CLEAR]",";");
        string[] aHospitalName;
        char[] splitter = { ';' };
        aHospitalName = tHospitalName.Split(splitter);
        string tMedicalSchool = Request.Form[GetHTMLNameById(hdnMedSch.ClientID, hdnMedSch.ID)];// Request.Form[GetHTMLNameById(lst_medsch.ClientID, lst_medsch.ID)];
        string tResidencyTraining = Request.Form[GetHTMLNameById(hdnRes.ClientID, hdnRes.ID)]; //txtResidency.Text.Replace("'", "''").Trim();
        string tGroupPractice = txtGroupPractise.Text.Replace("'", "''").Trim();
        string tInsurance = "";
        string tPhoto = txtPhoto.Text;
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["photo"])))
        {
            tPhoto = ViewState["photo"].ToString();
        }


        // if other Insurance companies added using the Add Button then get those also
        if (Session["InsId"] != null)
        {
            if (Session["InsId"].ToString().Trim().Length > 0)
            {
                if (tInsurance.Trim().Length <= 0)
                    tInsurance = Session["InsId"].ToString().Trim();
                else
                    tInsurance += "," + Session["InsId"].ToString().Trim();
            }
        }

        string tMsa = txtMsa.Text.Replace("'", "''").Trim();
        string tCmsa = txtCmsa.Text.Replace("'", "''").Trim();
        string tAbms_Certified = rbtAbms1.Checked ? "1" : "0";
        string tPrimarySpecialityID = Request.Form[GetHTMLNameById(hdnPSpecialty.ClientID, hdnPSpecialty.ID)].ToString(); //Request.Form[ddlPSpeciality.ClientID.Replace('_', '$')];
        string tSecondarySpecialityID = Request.Form[GetHTMLNameById(hdnSSpecialty.ClientID, hdnSSpecialty.ID)].ToString(); // Request.Form[ddlSSpeciality.ClientID.Replace('_', '$')];

        string tUPin = txtUpin.Text.Replace("'", "''").Trim();
        string tMajorActivityID = ddlMajorActivity.SelectedItem.Value;
        string tFellowShip = Request.Form[GetHTMLNameById(hdnFellow.ClientID, hdnFellow.ID)];
        string tAdvTraining = ddlAdvTraining.SelectedValue; //.Equals("1") ? "Y" : "N";
        string tAwards = txtAwards.Text.Replace("'", "''").Trim();
        # endregion

        if (!validateForm.CheckError())
        {
            e.Cancel = true;
            trError.Visible = true;
            errorlist.DataSource = validateForm.ErrList;
            errorlist.DataBind();
        }
        else { trError.Visible = false; }
        string sqlQuery = "";
        int id = Doctorid;
        int mark = 0;
        if (id == 0)
        {
            //Insert Query
            tbl_Doctor doc = new tbl_Doctor();
            doc.Id = CustomRepository.getMaxDootorId();
            int tId = doc.Id;
            tId++;
            mark = 1;
            sqlQuery = "SET NOCOUNT ON ";
            sqlQuery += "insert into tbl_doctors(Id,UPin,SpecialityID,PrimarySpecialityID,SecondarySpecialityID,";
            sqlQuery += "Abms_CertificationID,FName,MName,LName,Email,Title,Password,Phone,Fax";
            sqlQuery += ",Address1,Address2,City,State,CountryId,Languages,County,photo,Msa,Cmsa,";
            sqlQuery += "ZipCode,Gender,MedicalSchool,GraduationYear,MajorActivityID,";
            sqlQuery += "ResidencyTraining,GroupPractice,InsuranceIds,Fellowship,";
            sqlQuery += "AdvancedTraining,Awards,AcceptNew,Cost)values('";
            sqlQuery += tId + "','" + tUPin + "','" + tSpecialityID + "','" + tPrimarySpecialityID + "','" + tSecondarySpecialityID + "','" + tAbms_Certified + "','" + tFName + "','" + tMName + "','" + tLName + "','" + tEmail + "','" + tTitle + "','" + tPassword + "','" + tPhone + "','" + tFax + "','" + tAddress1 + "','" + tAddress2 + "','" + tCity + "','" + tState + "','" + tCountryId + "','" + tLanguages + "','" + tCounty + "','" + tPhoto + "','" + tMsa + "','" + tCmsa + "','" + tZipCode + "','" + tGender + "','" + tMedicalSchool + "','" + tGraduationYear + "','" + tMajorActivityID + "','" + tResidencyTraining + "','" + tGroupPractice + "','" + tInsurance + "','" + tFellowShip + "','" + tAdvTraining + "','" + tAwards + "'," + ddlnewPat.SelectedItem.Value + ",'" + tCost + "')";
            sqlQuery += "Select @@IDENTITY as Dr_ID";
        }
        else
        {            
            //Update Query
            mark = 2;
            sqlQuery = "update tbl_doctors set UPin='" + tUPin + "',SpecialityID='" + tSpecialityID;
            sqlQuery += "',PrimarySpecialityID='" + tPrimarySpecialityID + "',SecondarySpecialityID='" + tSecondarySpecialityID;
            sqlQuery += "',Abms_CertificationID='" + tAbms_Certified + "',FName='" + tFName;
            sqlQuery += "',MName='" + tMName + "',LName='" + tLName + "',Email='" + tEmail;
            sqlQuery += "',Title='" + tTitle + "',Password='" + tPassword + "',Phone='" + tPhone;
            sqlQuery += "',Fax='" + tFax + "',Address1='" + tAddress1 + "',Address2='" + tAddress2;
            sqlQuery += "',City='" + tCity + "',State='" + tState; // +"',CountryId='" + tCountryId;
            sqlQuery += "',Languages='" + tLanguages + "',County='" + tCounty + "',photo='" + tPhoto;
            sqlQuery += "',Msa='" + tMsa + "',Cmsa='" + tCmsa + "',ZipCode='" + tZipCode;
            sqlQuery += "',Gender='" + tGender + "',MedicalSchool='" + tMedicalSchool;
            sqlQuery += "',GraduationYear='" + tGraduationYear;
            sqlQuery += "',MajorActivityID='" + tMajorActivityID;
            sqlQuery += "',ResidencyTraining='" + tResidencyTraining + "',GroupPractice='" + tGroupPractice;
            sqlQuery += "',InsuranceIds='" + tInsurance;
            sqlQuery += "',Fellowship='" + tFellowShip;
            sqlQuery += "',AdvancedTraining='" + tAdvTraining;
            sqlQuery += "',Awards='" + tAwards;
            sqlQuery += "',AcceptNew=" + ddlnewPat.SelectedItem.Value;
            sqlQuery += ",Cost='" + tCost;
            sqlQuery += "' where id=" + id;
        }
        try
        {
            DataSet ds_id = new DataSet();
            StringBuilder sbSQL = new StringBuilder();

            //process to log admin activity - k: 30 April 2007
            SqlParameter[] sqlParam = new SqlParameter[3];
            sqlParam[0] = new SqlParameter("@Dr_ID", SqlDbType.Int);            
            sqlParam[1] = new SqlParameter("@AdminID", SqlDbType.Int);            
            sqlParam[2] = new SqlParameter("@ActionPerformed", SqlDbType.VarChar, 100);                          

            ds_id = mgr.ExecuteQuery(sqlQuery, "tbl");

            if (chechDentistInSub(id))
            {
                mgr.ExecuteScalarQuery("update tbl_DrPremium set photo ='" + tPhoto + "' where dr_id ='" + id + "'");
            }
            if (mark == 1)
            {
                id = Convert.ToInt32(ds_id.Tables[0].Rows[0]["Dr_ID"]);
                sqlParam[2].Value = "NEW DOCTOR ADDED";
            }
            // add hospitals & Insurance
            if (mark == 2)
            {
                string delSql = "delete tbl_Doctor_Hospital where Dr_ID='" + id + "';DELETE tbl_Doctor_Insurance WHERE DoctorID='" + id + "'";
                mgr.ExecuteScalarQuery(delSql); //Changed from executeQuery to ExecutescalarQuery by Deepak 19-12-2007
                sqlParam[2].Value = "DOCTOR UPDATED";
            }

            sqlParam[0].Value = id;
            sqlParam[1].Value = Convert.ToInt32(Session["ADMIN_ID"]);
            mgr.ExecuteUpdate("LOG_ADMIN_ACTIVITY", sqlParam);


            foreach (ListItem li in lstInsurance.Items)
            {
                if (li.Selected == true && li.Value != "-1")
                    sbSQL.Append("INSERT INTO tbl_Doctor_Insurance(DoctorID, InsuranceID) VALUES('" + id + "','" + li.Value + "');");
            }
            if (sbSQL.Length > 0)
                mgr.ExecuteUpdate(sbSQL.ToString());
            for (int i = 0; i < aHospitalName.Length; i++)
            {
                sqlParam = new SqlParameter[2];
                sqlParam[0] = new SqlParameter("@Dr_ID", SqlDbType.VarChar, 15);
                sqlParam[1] = new SqlParameter("@hospital", SqlDbType.VarChar, 500);

                sqlParam[1].Value = aHospitalName[i];
                sqlParam[0].Value = id;
                mgr.ExecuteUpdate("insert_doctorhospital", sqlParam);                               
            }

            

            Response.Redirect("./Ad_ManageDoctors.aspx");
        }
        catch (Exception es)
        {
            Response.Write(es.ToString());
        }
    }
    private bool chechDentistInSub(int id)
    {

        object objcount = mgr.ExecuteScalarQuery("select count(dr_id) from tbl_DrPremium where dr_id=" + id);
        if (Convert.ToString(objcount) != "0")
        {
            return true;
        }
        else
        {
            return false;

        }
    }
    protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        if (fupl_photo.HasFile)
        {
            string ImgPath1 = "~/images/Dr_images/";
            string filename1 = Path.GetFileName(fupl_photo.PostedFile.FileName);
            string baseFile = Path.GetFileNameWithoutExtension(fupl_photo.PostedFile.FileName);
            string extension = Path.GetExtension(fupl_photo.PostedFile.FileName);
            int fileMatchCount = 1;
            // Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
            while (File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1))))
            {
                //filename1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
                filename1 = string.Format("{0}({1:D2}){2}", baseFile, fileMatchCount, extension);
                fileMatchCount++;
            }
            fupl_photo.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1)));
            ViewState["photo"] = filename1;
        }

        int id = Doctorid;
        int counter = 0;
        string sql = "";
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        string medsch = "";
        string res = "";
        string fellow = "";
        string spId = "";
        string spec = "";
        string pSpId = "";
        string pSpec = "";
        string sSpId = "";
        string sSpec = "";
        string upin = "";
        string resId = "";
        string medId = "";
        string felId = "";
        string sCost = "";

        lnkResClear.Attributes.Add("onclick","document.getElementById('"+ lblRes.ClientID +"').innerHTML='NONE';document.getElementById('" + hdnRes.ClientID + "').value=''");
        SqlDataReader rdr = null;
        //mgr.BindList("select id,name from tbl_speciality order by name", "name", "id", ddlSpeciality, "select");


        //mgr.BindList("select id,name from tbl_primaryspeciality order by name", "name", "id", ddlPSpeciality, "select");
        //mgr.BindList("select id,name from tbl_secondaryspeciality order by name", "name", "id", ddlSSpeciality, "select");
        //mgr.BindListBox("select HName from tbl_hospitals where isdelete=0 order by Hname", "HName", "HName", lst_hospital, "select");
        //lst_hospital.Items.Add(new ListItem("--NONE--", "-1"));


        if (id != 0)
        {
            sb.Append("select D.Cost");
            sb.Append(",D.GraduationYear");
            sb.Append(",S.Id AS SID, S.[Name] AS Speciality");
            sb.Append(",P.Id AS PID,P.[Name] AS PSpeciality");
            sb.Append(",SS.Id AS SSID,SS.[Name] AS SSpeciality");
            sb.Append(",D.Medicalschool AS mId, M.MedicalSchool");
            sb.Append(",D.ResidencyTraining AS rId, dbo.getMedicalSchool(D.ResidencyTraining) AS ResidencyTraining");
            sb.Append(",D.Fellowship AS fId, dbo.getFellowship(D.Fellowship) AS Fellowship");
            sb.Append(",D.Upin");
            sb.Append(" from tbl_doctors as D");
            sb.Append(" left outer join tbl_Speciality AS S ON D.SpecialityID = S.Id");
            sb.Append(" left outer join tbl_PrimarySpeciality AS P ON D.PrimarySpecialityID = P.Id");
            sb.Append(" left outer join tbl_SecondarySpeciality AS SS ON D.SecondarySpecialityID = SS.Id");
            sb.Append(" left outer join tbl_MedicalSchool AS M ON M.Id = D.MedicalSchool");
            sb.Append(" WHERE D.Id =" + id);

            sql = sb.ToString();
            lblMedSch.Visible = true;
            lblRes.Visible = true;
            lblFellow.Visible = true;
            rdr = mgr.ExecuteQuery(sql);
            if (rdr.Read())
            {
                medsch = rdr["MedicalSchool"].ToString();
                medId = rdr["mId"].ToString();
                res = rdr["ResidencyTraining"].ToString();
                resId = rdr["rId"].ToString();
                fellow = rdr["Fellowship"].ToString();
                felId = rdr["fId"].ToString();
                spId = rdr["SID"].ToString();
                spec = rdr["Speciality"].ToString();
                pSpId = rdr["PID"].ToString();
                pSpec = rdr["PSpeciality"].ToString();
                sSpId = rdr["SSID"].ToString();
                sSpec = rdr["SSpeciality"].ToString();
                upin = rdr["Upin"].ToString();
                sCost = rdr["Cost"].ToString();
            }
            rdr.Close();
            sql = "SELECT H.HName FROM tbl_Hospitals AS H, tbl_doctor_hospital AS D WHERE D.dr_id = " 
                + id + "AND D.IsDelete=0 AND H.IsDelete=0 AND D.hospital_id = H.Id";
            rdr = mgr.ExecuteQuery(sql);
            while (rdr.Read())
            {
                counter = counter + 1;
                
                // Modified on 12-july-2007 by ad functionality has been added to individually delete an hospital from a label control
                if (!rdr["HName"].ToString().Equals(""))
                {
                    hospTEXT += rdr["HName"].ToString() + "[Clear]";
                    hospName += rdr["HName"].ToString() + "<a id=mLnk~" + counter + " href=\"javascript:void(0)\" onclick=\"ReplaceText('mLnk~" + counter + "')\" > [Clear]</a>" + "<BR>";
                }
                
            }
            rdr.Close();
            if (hospName.Contains("<BR>")) // check for <BR> tag at the end of string, if found needs to be delete in order to avoid blank save
            {
                // must be done for prompt results
                int idx = hospName.LastIndexOf("<BR>");
                hospName= hospName.Remove(idx, 4);
                
            }
            
            if (!medsch.Trim().Equals(""))
            {
                lblMedSch.Text = medsch;
                hdnMedSch.Value = medId;
            }
            if (!res.Trim().Equals(""))
            {
                lblRes.Text = res;
                hdnRes.Value = resId;
            }
            if (!fellow.Trim().Equals(""))
            {
                lblFellow.Text = fellow;
                hdnFellow.Value = felId;
            }
            if (!spec.Trim().Equals(""))
                lblSpeciality.Text = spec;
            if (!pSpec.Trim().Equals(""))
                lblPSpeciality.Text = pSpec;
            if (!sSpec.Trim().Equals(""))
                lblSSpeciality.Text = sSpec;
            if (!hospName.Trim().Equals(""))
            {
                lblHospital.Text = hospName;
                hdnHospital.Value = hospTEXT;
            }
            hdnSpecialty.Value = spId;
            hdnPSpecialty.Value = pSpId;
            hdnSSpecialty.Value = sSpId;
            txtUpin.Text = upin;
            ddlCost.SelectedValue = sCost;
        }

        //to hold password in viewstate
        ViewState["Pwd"] = txtPwd1.Text.Replace("'", "''");        

        // checking for duplicate email when inserting a new record                  
        if (id == 0)
        { sql = "select 1,isBulk from tbl_doctors where email='" + txtEmail.Text + "' and  isdelete=0 "; }
        else
        { sql = "select 1,isBulk from tbl_doctors where email='" + txtEmail.Text + "' and id<>" + id + " and  isdelete=0 "; }
        DataSet dsEmail = CustomRepository.CustumDataSetFunction(sql, "tbl");
            //mgr.ExecuteQuery(sql, "tbl");
        
        if (dsEmail.Tables[0].Rows.Count > 0)
        {
            if (!Convert.ToBoolean(dsEmail.Tables[0].Rows[0]["isBulk"]))
            {
                trError.Visible = true;
                errorlist.Items.Add("Email already exists!! Please try with a different email id.");
                e.Cancel = true;
                //if (ViewState["email"] != null)
                //{ txtEmail.Text = ViewState["email"].ToString(); }
                return;
            }
        }
        else
        {
            trError.Visible = false;
        }

        // end checking for duplicate email  
        //Add server side validation 
        Validation validateForm = new Validation();
        validateForm.AddValidation(txtFname.Text.Trim(), Validation.ValidationCommand.required, "Please Enter First Name.", "");

        validateForm.AddValidation(txtLName.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Last Name.", "");

        //check for bulk upload, because incase of a bulk upload editing validation is not mandatory for username and password : K
        //5th November 2006

        //Commeneted below line at 280808 by ranjeet to update a doctors  profile without entering an email and password

        //bool isBulk = Convert.ToBoolean(mgr.ExecuteScalarQuery("select isbulk from tbl_doctors where id=" + Doctorid.ToString()));

        //if ((!isBulk)&&(id>0))

        //End

        if ((id > 0))
        {
            if (txtEmail.Text.Trim() != "")  
            {
                validateForm.AddValidation(txtEmail.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Email.", "");
                validateForm.AddValidation(txtEmail.Text.Trim(), Validation.ValidationCommand.email, "Please Enter Correct Email", "");
            }
            if (txtPwd1.Text.Trim() != "")
            {
                validateForm.AddValidation(txtPwd1.Text, Validation.ValidationCommand.required, "Please Enter Password.", "");
                validateForm.AddValidation(txtPwd1.Text, Validation.ValidationCommand.minlen, "Please Enter  atleast 6 characters in Password.", "6");
                validateForm.AddValidation(txtpwd2.Text, Validation.ValidationCommand.required, "Please Enter Confirm Password", "");
            }

            
        }
        //k-code ends
        validateForm.AddValidation(txtTitle.Text.Trim(), Validation.ValidationCommand.required, "Please Enter title.", "");
        validateForm.AddValidation(txtAddress1.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Address1.", "");
        validateForm.AddValidation(txtCity.Text.Trim(), Validation.ValidationCommand.required, "Please Enter city.", "");

        validateForm.AddValidation(txtZipCode.Text.Trim(), Validation.ValidationCommand.required, "Please Enter zip code.", "");
        validateForm.AddValidation(txtAddress1.Text.Trim(), Validation.ValidationCommand.maxlen, "Address Maximum Length is Only 100 Characters", "99");
        validateForm.AddValidation(txtAddress2.Text.Trim(), Validation.ValidationCommand.maxlen, "Address Maximum Length is Only 100 Characters", "99");

        validateForm.AddValidation(ddlState.Text.Trim(), Validation.ValidationCommand.notequal, "Please Select State", "0");
        validateForm.AddValidation(txtCity.Text.Trim(), Validation.ValidationCommand.alphabetic, "Please enter Correct City Name.", "");

        validateForm.AddValidation(txtPhone.Text.Trim(), Validation.ValidationCommand.phone, "Please Enter Correct Telephone Number", "");
        
        if (!validateForm.CheckError())
        {
            e.Cancel = true;
            trError.Visible = true;
            errorlist.DataSource = validateForm.ErrList;
            errorlist.DataBind();
        }
        else { trError.Visible = false; }

    }

    protected void btnAddInsurance_Click(object sender, EventArgs e)
    {

    }

    //Function to get the HTML name of the server control from the Client Id
    // Parameters: 
    //  clientId - Control.ClientId
    //  serverId - Control.id
    private string GetHTMLNameById(string clientId, string serverId)
    {
        int pos = serverId.IndexOf('_');
        string HTMLName = "";
        if(pos >= 0)
        {
            pos = clientId.IndexOf(serverId);
            HTMLName = clientId.Remove(pos, serverId.Length);
            HTMLName = HTMLName.Replace('_', '$');
            HTMLName += serverId;
        }
        else
            HTMLName = clientId.Replace('_', '$');
        return HTMLName;
    }
    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        string countryID = ddlCountry.SelectedValue;
        // mgr.BindList("select countrycode,countryname from tbl_country", "countryname", "countrycode", ddlCountry, "select");
        mgr.BindList("select stateid,name from tbl_states where CountryID='" + countryID + "'  order by name", "Name", "StateId", ddlState, "-- Any --");
        // mgr.BindList("select stateid,name from tbl_states order by name", "Name", "StateId", ddlState, "-- Any --");
        if (ddlCountry.SelectedValue == "US")
        {
            ddlState.Items.Insert(0, new ListItem("Select a State", "0"));
        }
        else
        {
            ddlState.Items.Insert(0, new ListItem("Select a Province", "0"));
        }
    }
}

